package com.infindo.appcreate.zzyj.hibernet;

import java.util.Properties;

import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.tool.hbm2x.Cfg2JavaTool;
import org.hibernate.tool.hbm2x.pojo.EntityPOJOClass;

/**
 * This class extends EntityPOJOClass in order to override the generation of
 * sequence generators. It retreives the settings for sequence and generator
 * from properties already set inside the Reverse Engineering Strategy
 * 
 * @author Nikolai Gagov
 * 
 */
public class CustomEntityPojoClass extends EntityPOJOClass {

	public CustomEntityPojoClass(PersistentClass clazz, Cfg2JavaTool cfg) {
		super(clazz, cfg);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.hibernate.tool.hbm2x.pojo.POJOClass#generateAnnIdGenerator()
	 */
	@Override
	public String generateAnnIdGenerator() {

		final KeyValue identifier = ((PersistentClass) getDecoratedObject())
				.getIdentifier();

		if (identifier instanceof SimpleValue) {

			final SimpleValue simpleValue = (SimpleValue) identifier;

			final String strategy = simpleValue
					.getIdentifierGeneratorStrategy();

			if ("sequence".equals(strategy)) {

				final Properties properties = simpleValue
						.getIdentifierGeneratorProperties();

				final String generatorName = properties.getProperty(
						"generatorName", "");

				final StringBuffer wholeString = new StringBuffer("    ");

				final StringBuffer id = new StringBuffer().append("@").append(
						importType("javax.persistence.Id"));

				id.append(" @")
						.append(importType("javax.persistence.GeneratedValue"))
						.append('(')
						.append("strategy=")
						.append(staticImport(
								"javax.persistence.GenerationType", "SEQUENCE"))
						.append(", generator=\"").append(generatorName)
						.append("\"").append(')');

				buildAnnSequenceGenerator(wholeString, properties);

				wholeString.append(id);

				return wholeString.toString();
			}
		}

		return super.generateAnnIdGenerator();
	}

	private void buildAnnSequenceGenerator(StringBuffer wholeString,
			Properties properties) {
		wholeString
				.append("@")
				.append(importType("javax.persistence.SequenceGenerator")
						+ "(name=\""
						+ properties.getProperty("generatorName", "")
						+ "\", sequenceName=\"")
				.append(properties.getProperty(
						org.hibernate.id.SequenceGenerator.SEQUENCE, ""))
				.append("\")").append("\n    ");
	}
}
